<template>
  <view class="page">
    <!-- 自定义日期 -->
    <customRange @update-between-time="handleBetweenTime" @between-choose-index="handleBetweenTimeChoose" class="header">
      <template v-slot:custom>
        <view style="padding: 0 30rpx;padding-bottom: 20rpx;" class="flex-ali-cen">
          <picker @change="bindPickerChangeShop" :value="shopIndex"
                  :range="shopList.map(item=>item.shop_alias)">
            <view class="flex-row flex-jus-bet" style="width: 100%;flex: 1">
              <view class="flex-row">
                <view class="f-s-28" style="color: var(--grey-text);">当前门店：</view>
                <view class="f-s-28" style="color: var(--white-text);align-items: center;">
                  {{ shopList[shopIndex].shop_alias }}
                </view>
              </view>
              <view class="flex-row">
                <view class="f-s-28" style="color: #0A84FF;align-items: center">
                  切换门店
                </view>
                <view style="margin-left: 4rpx">
                  <uni-icons type="down" size="14" color="#0A84FF"></uni-icons>
                </view>
              </view>

            </view>
          </picker>
        </view>
      </template>
    </customRange>

    <scroll-view class="scroll" scroll-y @refresherrefresh="refresher" refresher-enabled="true"
                 :refresher-background="bgColorRefresh" :refresher-triggered="triggered" :refresher-threshold="80"
                 @scrolltolower="finishPullUp" :show-scrollbar="false" :style="{'top':topHeight+'px','height':scrollHeight}">
      <view class="body-child p-t-26">
        <!-- 业绩汇总 -->
        <view class="total-content">
          <view class="total-content-area">
            <view class="total-content-title">
              <view class="total-content-title-font">业绩汇总</view>
              <view class="radio-group">
                <radio-group @change="radioChange">
                  <label class="radio-item" style="margin-right: 20rpx;">
                    <radio value="1" :checked="radioValue == 1" active-background-color="#ff6f3f"
                           activeBorderColor="#ff6f3f" borderColor="#333"
                           style="transform: scale(0.7);">
                    </radio>
                    <text class="radio-label">简要模式</text>
                  </label>
                  <label class="radio-item">
                    <radio value="2" :checked="radioValue == 2" active-background-color="#ff6f3f"
                           activeBorderColor="#ff6f3f" borderColor="#333"
                           style="transform: scale(0.7);">
                    </radio>
                    <text class="radio-label">详细模式</text>
                  </label>
                </radio-group>
              </view>
            </view>
            <view class="line-split"></view>
            <view class="total-content-body">
              <view style="display: flex;flex-direction: row;align-items: center;">
                <view class="total-content-intro">业绩目标：</view>
                <view class="total-content-value">
                  {{ formatNumber(departPerformanceTotal.performance_objectives) || 0 }}
                </view>
                <view class="total-content-value">
                  （{{ formatNumber(departPerformanceTotal.objectives_rate) || 0 }}%）
                </view>
              </view>
            </view>
            <view class="total-content-body-next">
              <view class="total-content-next-value">
                <view class="total-content-value">
                  {{ formatNumber(departPerformanceTotal.fact_performance) || 0 }}
                </view>
                <view class="total-content-intro intro-margin">实际业绩</view>
              </view>
              <view class="total-content-next-value">
                <view class="total-content-value">{{ formatNumber(departPerformanceTotal.all_number) || 0 }}
                </view>
                <view class="total-content-intro intro-margin">实际订桌</view>
              </view>
              <view class="total-content-next-value">
                <view class="total-content-value">
                  {{ formatNumber(departPerformanceTotal.charge_money) || 0 }}
                </view>
                <view class="total-content-intro intro-margin">充值业绩</view>
              </view>
              <view class="total-content-next-value">
                <view class="total-content-value">
                  {{ formatNumber(departPerformanceTotal.commission_money) || 0 }}
                </view>
                <view class="total-content-intro intro-margin">商品提成</view>
              </view>
            </view>
          </view>
        </view>
        <!-- 部门筛选 -->
        <view class="depart-content">
          <view style="display: flex;flex-direction: row;height: 100%;align-items: center;">
            <view class="depart-content-title"
                  :class="{ 'depart-content-title-active': changeView === 'depart' }"
                  @click="changeContent('depart')">部门业绩
            </view>
            <view class="depart-content-title depart-content-sub-title"
                  :class="{ 'depart-content-title-active': changeView === 'person' }"
                  @click="changeContent('person')">
              人员业绩
            </view>
          </view>
          <view style="display: flex;flex-direction: row;height: 100%;align-items: center;">
            <view class="depart-content-field">
              <view class="depart-content-rule">
                <picker @change="bindPickerChange" :value="ruleIndex" :range="ruleArray">
                  <view class="depart-content-rule">{{ ruleArray[ruleIndex] }}</view>
                </picker>
              </view>
              <uni-icons type="down" size="12" :color="iconColor"></uni-icons>
            </view>
            <view class="depart-content-field" style="margin-left: 20rpx;" @click="changeRule">
              <view class="depart-content-rule">{{ rule.key }}</view>
              <uni-icons :type="rule.icon" size="12" :color="iconColor"></uni-icons>
            </view>
          </view>
        </view>
        <!-- 筛选以及搜索条件 -->
        <view class="depart-tree-content">
          <view style="display: flex;flex-direction: row;height: 66rpx;line-height: 66rpx;"
                @click="showDepart">
            <view class="depart-content-rule">所有部门</view>
            <uni-icons type="down" size="12" :color="iconColor"></uni-icons>
          </view>
          <view class="depart-search">
            <input class="uni-input" :placeholder="placeholderInput"
                   placeholder-style="font-size:24rpx;text-indent:26rpx" adjust-position="false" cursor="20"
                   selection-start="20"
                   v-model="keword_search" style="color: var(--white-text)" @confirm="handleSearchClick"/>
            <view class="depart-content-rule" style="margin-left: 8rpx;" @click="handleSearchClick">搜索
            </view>
          </view>
        </view>
        <!-- 部门业绩 -->
        <view v-if="changeView === 'depart'">
          <depart-sales :radioValue="radioValue" :departPerformanceList="departPerformanceList"
                        :iconColor="iconColor" :format-number="formatNumber"
                        @choose-depart="handleChooseDepart"></depart-sales>
        </view>
        <!-- 人员业绩 -->
        <view v-if="changeView === 'person'">
          <person-sales :radioValue="radioValue" :personPerformanceList="personPerformanceList"
                        :iconColor="iconColor" :format-number="formatNumber" :loadingFlag="loadingFlag"
                        @choose-person="handleChoosePerson"></person-sales>
        </view>
        <view class="load-bottom" v-if="changeView == 'person'">
          <view v-if="loadingFlag == 1" class="load_in" :class="loadingFlag == 1 ? 'load_in_ani' : ''">
            <uni-icons type="spinner-cycle" size="30" color="#ff6f3f"></uni-icons>
          </view>
          <view v-show="loadingFlag == 2" class="load_over">数据已全部加载~</view>
        </view>
      </view>
    </scroll-view>
    <!-- 部门弹窗 -->
    <view>
      <uni-popup ref="popupDepart" type="bottom" :background-color="bgColor">
        <view>
          <view class="depart-sure-cancel">
            <view style="font-size: 28rpx;color: rgb(150 148 148)" @click="cancelDepart">取消</view>
            <view style="color: #8383ff;font-size: 28rpx;" @click="sureDepart">确定</view>
          </view>
          <view class="line-split"></view>
          <view class="depart-all-choose" style="">
            <view class="font-28 text-white-black">
              所有部门
            </view>
            <view>
              <checkbox-group @change="changeAllStatus">
                <checkbox :checked="checkboxAll" value="all"/>
              </checkbox-group>
            </view>
          </view>
          <view class="depart-child-item">
            <checkbox-group @change="changeItemStatus">
              <view class="depart-popup-content" v-for="(item,index) in departList" :key="index">
                <view class="font-28 text-white-black">
                  {{ item.depart_name }}
                </view>
                <view>
                  <checkbox :value="String(item.depart_id)" :checked="item.checked"/>
                </view>
              </view>
            </checkbox-group>
          </view>
        </view>
      </uni-popup>
    </view>
  </view>
  <custom-loading-vue ref="loadings"></custom-loading-vue>
</template>

<script setup>
import {
  onLoad
} from '@dcloudio/uni-app'
import {
  ref,
  watch,
  onMounted,
  getCurrentInstance
} from 'vue'
import customRange from '@/components/customRange.vue'
import departSales from '@/pages/application/sales_performance_child/departSales.vue'
import personSales from '@/pages/application/sales_performance_child/personSales.vue'
import customLoadingVue from '@/components/customLoading.vue'
const instance = getCurrentInstance()
const commonJs = instance?.proxy?.$commonJs
const shopIndex = ref(commonJs.getChooseShopIndex())
const shopList = ref(commonJs.getShopList())
const userInfo = commonJs.getUserInfo()
const loadings = ref(null)
const triggered = ref(false)
const betweenTime = ref([])
const betweenTimeIndex = ref(0)
const handleBetweenTime = (timeRange) => {
  betweenTime.value = timeRange
}
const handleBetweenTimeChoose = (index) => {
  betweenTimeIndex.value = index
}
const changeView = ref('depart')
const radioValue = ref(uni.getStorageSync('sales_type') || '1')
const departPerformanceList = ref([])
const personPerformanceList = ref([])
const departPerformanceTotal = ref({
  performance_objectives: 0,
  objectives_rate: 0,
  fact_performance: 0,
  all_number: 0,
  charge_money: 0,
  commission_money: 0
})
const departList = ref([])
const sort = ref({
  sort_key: "fact_performance",
  sort_rule: "desc"
})
const iconColor = ref('var(--grey-text)')
const bgColor = ref('var(--area-color)')
const bgColorRefresh = ref('var(--bg-color)')
const rule = ref({
  key: '降序',
  value: 'desc',
  icon: 'arrow-down'
})
const keword_search = ref('')
const ruleArray = ref(['消费业绩', '充值业绩', '实际订桌', '目标业绩', '桌均消', '人均业绩'])
const ruleArrayValue = ref(['fact_performance', 'charge_money', 'all_effective_count', 'performance_objectives',
  'room_avg_money', 'staff_avg_money'
])
const ruleIndex = ref(0)
const popupDepart = ref(Object)
const checkboxAll = ref(false)
const chooseDepartIds = ref([])
const placeholderInput = ref('请输入部门进行检索')
const pagesData = ref({
  page: 1,
  limit: 15,
  total: 0
})
const loadingFlag = ref(0)
const topHeight = ref(0)
const scrollHeight = ref(0)

onMounted(() => {
  const query = uni.createSelectorQuery().in(this);
  query.select(".header")
      .boundingClientRect((data) => {
        topHeight.value = data.height
        let height = '100vh',
            top = data.height + 'px'
        scrollHeight.value = `calc(${height} - ${top})`
      })
      .exec();
})

onLoad((e) => {

})

/**
 * 日期监听
 */
watch(betweenTime, (newValue, oldValue) => {
  if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
    if (changeView.value === 'depart'){
      getPerformanceDataDepart()
    }else{
      resetPages()
      getPerformanceDataPerson()
    }
  }
}, {
  deep: true
})

/**
 * 门店切换
 * @param e
 */
const bindPickerChangeShop = (e) => {
  if (e.detail.value >= 0 && e.detail.value != commonJs.systemConfig.shopIndex) {
    shopIndex.value = e.detail.value
    commonJs.systemConfig.shopIndex = e.detail.value
    commonJs.setStorage(
        'shopIndex',
        e.detail.value,
        function () {
          commonJs.logger.debug('设置门店成功！')
        }
    )
    if (changeView.value === 'depart'){
      getPerformanceDataDepart()
    }else{
      resetPages()
      getPerformanceDataPerson()
    }
  }
}

/**
 * 切换应用
 * @param view 页面标识
 */
const changeContent = (view) => {
  keword_search.value = ''
  placeholderInput.value = view === 'depart' ? '请输入部门进行检索' : '请输入人员进行检索'
  changeView.value = view
  if (view === 'depart') {
    if (!ruleArray.value.includes('人均业绩')) {
      ruleArray.value.push('人均业绩')
      ruleArrayValue.value.push('staff_avg_money')
    }
    getPerformanceDataDepart()
  } else {
    const index = ruleArray.value.indexOf('人均业绩')
    if (index !== -1) {
      ruleArray.value.splice(index, 1)
      ruleArrayValue.value.splice(index, 1)
    }
    resetPages()
    getPerformanceDataPerson()
  }
}

/**
 * 展示部门
 */
const showDepart = () => {
  popupDepart.value.open()
}

/**
 * 取消部门
 */
const cancelDepart = () => {
  popupDepart.value.close()
}

/**
 * 确定选择的销售部门
 */
const sureDepart = () => {
  popupDepart.value.close()
  if (changeView.value === 'depart'){
    getPerformanceDataDepart()
  }else{
    resetPages()
    getPerformanceDataPerson()
  }

}

/**
 * 模式切换
 * @param v
 */
const radioChange = (v) => {
  if (v.detail.value === '1' || v.detail.value === '2') {
    radioValue.value = v.detail.value;
    uni.setStorageSync('sales_type', v.detail.value)
    if (changeView.value === 'depart'){
      getPerformanceDataDepart()
    }else{
      resetPages()
      getPerformanceDataPerson()
    }
  }
}

/**
 * 获取部门销售业绩
 */
const getPerformanceDataDepart = () => {
  const departIds = departList.value.filter(item => item.checked).map(item => item.depart_id)
  if (departIds !== '' && Array.isArray(departIds) && departIds.length > 0) {
    chooseDepartIds.value = departIds
  }
  const params = {
    begin_date: betweenTime.value[0] + ' 12:00:00',
    end_date: betweenTime.value[1] + ' 12:00:00',
    depart_id: departIds !== '' && Array.isArray(departIds) && departIds.length > 0 ? departIds.join() : '',
    search: keword_search.value,
    sort_key: ruleArrayValue.value[ruleIndex.value],
    sort_rule: rule.value.value,
    phone: userInfo.phone
  }
  commonJs.queryCache('/app/admin/salesDepartKPI', params, {
    before() {
      loadings.value.show('加载中...')
    },
    success(res) {
      try {
        const {
          code,
          data,
          msg,
          server_ip
        } = res
        if (data.hasOwnProperty('all_depart')) {
          filterDepartChoose(departIds, data.all_depart)
        }
        if (data.hasOwnProperty('depart')) {
          departPerformanceList.value = data.depart
        }
        if (data.hasOwnProperty('total')) {
          departPerformanceTotal.value = data.total
        }
      } catch (error) {
        commonJs.logger.debug(error, 'error')
      }
    },
    fail(err) {
      commonJs.logger.debug(err, 'error')
    },
    complete(){
      loadings.value.hide()
    }
  }, {"X-Merchant-ID": shopList.value[shopIndex.value].shop_id})
}

/**
 * 获取人员销售业绩
 */
const getPerformanceDataPerson = (depart_id = null) => {
  const departIds = departList.value.filter(item => item.checked).map(item => item.depart_id)
  if (departIds !== '' && Array.isArray(departIds) && departIds.length > 0) {
    chooseDepartIds.value = departIds
  }
  let depart_ids = ''
  if (!depart_id) {
    depart_ids = departIds !== '' && Array.isArray(departIds) && departIds.length > 0 ? departIds
        .join() : '' || 0
  } else {
    depart_ids = depart_id
  }
  const params = {
    begin_date: betweenTime.value[0] + ' 12:00:00',
    end_date: betweenTime.value[1] + ' 12:00:00',
    depart_id: depart_ids,
    search: keword_search.value,
    order_name: ruleArrayValue.value[ruleIndex.value],
    sort: rule.value.value,
    limit: pagesData.value.limit,
    page: pagesData.value.page,
    phone: userInfo.phone
  }
  commonJs.queryCache('/app/admin/salesKPI', params, {
    before() {
      loadings.value.show('加载中...')
    },
    success(res) {
      try {
        const {
          code,
          data,
          msg,
          server_ip
        } = res
        if (data.hasOwnProperty('list') && data.hasOwnProperty('count')) {
          personPerformanceList.value = [...personPerformanceList.value, ...data.list]
          pagesData.value.total = data.count
        }
      } catch (error) {
        commonJs.logger.debug(error, 'error')
      }
    },
    fail(err) {
      commonJs.logger.debug(err, 'error')
    },
    complete(){
      loadings.value.hide()
      setTimeout(()=>{
        loadingFlag.value = 0
      },250)
    }
  }, {"X-Merchant-ID": shopList.value[shopIndex.value].shop_id})
}

/**
 * 部门赋值
 * @param departIds 选中的部门ID集合
 * @param allDepart 获取的部门列表信息
 */
const filterDepartChoose = (departIds, allDepart) => {
  // 已勾选的部门选中
  departList.value = allDepart.map(item => {
    if (departIds.length > 0 && departIds.includes(item.depart_id)) {
      item.checked = true
    }
    return item
  })
  // 是否需要勾上全选操作
  const chooseStatus = departList.value.filter(item => !item.checked)
  checkboxAll.value = Array.isArray(chooseStatus) && chooseStatus.length === 0 ? true : false
}

/**
 * 条件排序
 */
const changeRule = () => {
  rule.value = rule.value.value === 'desc' ? {
    key: '升序',
    value: 'asc',
    icon: 'arrow-up'
  } : {
    key: '降序',
    value: 'desc',
    icon: 'arrow-down'
  }
  if (changeView.value === 'depart'){
    getPerformanceDataDepart()
  }else{
    resetPages()
    getPerformanceDataPerson()
  }
}

/**
 * 切换排序规则
 * @param e 选择的索引
 */
const bindPickerChange = (e) => {
  ruleIndex.value = e.detail.value
  if (changeView.value === 'depart'){
    getPerformanceDataDepart()
  }else{
    resetPages()
    getPerformanceDataPerson()
  }
}

/**
 * 所有部门勾选  全选 反选操作
 * @param e 选中的值
 */
const changeAllStatus = (e) => {
  departList.value = departList.value.map(item => {
    if (e.detail.value.length > 0) {
      item.checked = true
    } else {
      item.checked = false
    }
    return item
  })
}

/**
 * 子部门选择
 * @param e 选中值
 */
const changeItemStatus = (e) => {
  let chooseIdArray = e.detail.value
  departList.value = departList.value.map((item) => {
    if (chooseIdArray.includes(String(item.depart_id))) {
      item.checked = true
    } else {
      item.checked = false
    }
    return item
  })
}

/**
 * 格式化处理
 * @param money
 * @returns {string|*}
 */
const formatNumber = (money) => {
  // 判断是否为整数（即小数部分是否为 0）
  if (money % 1 === 0) {
    return Number(money).toString()
  } else {
    return Number(money).toFixed(2)
  }
}

const handleSearchClick = () => {
  if (changeView.value === 'depart') {
    getPerformanceDataDepart()
  } else {
    resetPages()
    getPerformanceDataPerson()
  }
}

const handleChooseDepart = (item) => {
  if (item.depart_id == 0) {
    uni.showToast({
      title: '自来客移步到后台查看',
      icon: 'none',
      duration: 1500
    })
    return
  }
  item.all_number = item.all_effective_count
  departPerformanceTotal.value = item
  resetPages()
  getPerformanceDataPerson(item.depart_id)
  changeView.value = 'person'
}

const handleChoosePerson = (item) => {
  if (item.salesman_id == 0) {
    uni.showToast({
      title: '自来客移步到后台查看',
      icon: 'none',
      duration: 1500
    })
    return
  }
  uni.navigateTo({
    url: '/pages/application/sales_performance_person?betweenTime=' + JSON.stringify(betweenTime
        .value) + '&staff=' + JSON.stringify(item) + '&index=' + betweenTimeIndex.value
  })
}

const refresher = async (e) => {
  if (!triggered.value) {
    triggered.value = true
    if (changeView.value === 'depart'){
      getPerformanceDataDepart()
    }else{
      resetPages()
      getPerformanceDataPerson()
    }
    setTimeout(() => {
      triggered.value = false
    }, 500)
  }
}

const resetPages = () => {
  pagesData.value.page = 1
  loadingFlag.value = 0
  personPerformanceList.value = []
}

const finishPullUp = (e) => {
  if (loadingFlag.value == 1 || loadingFlag.value == 2 || changeView.value == 'depart') {
    return
  }
  let pages = Math.ceil(pagesData.value.total / pagesData.value.limit)
  if (pagesData.value.page >= pages) {
    loadingFlag.value = 2
    return
  }
  if (loadingFlag.value == 0) {
    loadingFlag.value = 1
    pagesData.value.page++
    getPerformanceDataPerson()
  }
}

</script>
<style scoped>
.scroll {
  box-sizing: border-box;
  display: flex;
  position: absolute;
  padding: 4rpx 0;
}

.depart-child-item {
  display: flex;
  flex-direction: column;
  overflow: auto;
  max-height: 1000rpx;
  min-height: 500rpx;
}

.depart-all-choose {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 70rpx;
  line-height: 70rpx;
  padding: 0 30rpx;
}

.depart-sure-cancel {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 0 30rpx;
  height: 70rpx;
  line-height: 70rpx;
}

.depart-content-field {
  display: flex;
  flex-direction: row;
  height: 66rpx;
  line-height: 66rpx;
}

.depart-tree-content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 0 30rpx;
  margin-top: 10rpx;
}

.depart-search {
  flex: 1;
  display: flex;
  flex-direction: row;
  height: 66rpx;
  line-height: 66rpx;
  align-items: center;
  margin-left: 20rpx;
}


.total-content {
  height: 264rpx;
  padding: 0 30rpx;
}


.depart-content {
  padding: 0 30rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 66rpx;
  align-items: center;
  margin: 16rpx 0 16rpx 0;
}

.depart-content-title {
  height: 66rpx;
  line-height: 66rpx;
  color: var(--grey-text);
  font-size: 28rpx;
}

.depart-content-title-active {
  border-bottom: 2px solid var(--white-text);
  color: var(--white-text);
  font-weight: 600;
}

.depart-content-sub-title {
  margin-left: 30rpx;
}

.depart-content-rule {
  font-size: 28rpx;
  color: var(--grey-text);
}

.total-content-next-value {
  display: flex;
  flex-direction: column;
  flex: 1;
  justify-content: center;
  align-items: center;
}

.total-content-area {
  height: 264rpx;
  background-color: var(--bg-center-color);
  border-radius: 20rpx;
  padding: 0 20rpx;
  display: flex;
  flex-direction: column;
}

.intro-margin {
  margin-top: 18rpx;
}

.total-content-title {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 72rpx;
  align-items: center;
}

.total-content-title-font {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--white-text);
}

.total-content-value {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--white-text);
}

.total-content-body {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-top: 20rpx;
  height: 40rpx;
}

.total-content-body-next {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-top: 20rpx;
}

.total-content-intro {
  font-size: 24rpx;
  color: var(--grey-text);
}

.radio-group {
  display: flex;
  flex-direction: row;
}

.radio-item {
  display: flex;
  align-items: center;
  flex-direction: row;
}

:deep(uni-radio-group) {
  display: flex;
  flex-direction: row;
}

.radio-label {
  margin-left: 8px;
  font-size: 24rpx;
  color: var(--grey-text);
}

.uni-input {
  background-color: var(--bg-center-color);
  border-radius: 30rpx;
  width: 100%;
  display: flex;
  height: 60rpx;
  flex: 1
}

:deep(.uni-input-input) {
  text-indent: 30rpx !important;
  font-size: 26rpx !important;
}

.depart-popup-content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 70rpx;
  line-height: 70rpx;
  padding: 0 30rpx 0 80rpx;
}

:deep(checkbox uni-checkbox::before) {
  color: var(--area-color) !important;
  z-index: 102;
  border: 1px solid var(--area-color);
}

:deep(.uni-checkbox-wrapper .uni-checkbox-input) {
  background-color: var(--area-color) !important;
  z-index: 102;
}
</style>